import { defineComponent, ref, watch } from "vue";
/* hooks */
import { useDialog } from "@hooks/useDialog";
import { useState } from '@src/modules/trigger/hooks/useVC'
/* model */
import { CreateTriggerDialogFormFields, TriggerWayListItem } from '@src/modules/trigger/model'
import Field from "@model/entity/Field";
/* utils */
import { initialize } from '@src/component/form/util/index'
import i18n from '@src/locales'
/* http */
import {getAllExecuteWayList} from '@src/modules/trigger/api/trigger.js'
/* style */
import '@src/modules/trigger/components/CreateTriggerDialog/style.scss'



export default defineComponent({
    setup(props, { emit, expose }) {
        const formRef = ref(null)
        const [formFields, setFormFields] = useState(CreateTriggerDialogFormFields);
        const [formValue, setFormValue] = useState(initialize(formFields.value, {}));
        const { visible, showDialog, hideDialog } = useDialog()
        // 默认选中第一个
        const [triggerActiveIndex, setTriggerActiveIndex] = useState(0)
        const TriggerWayList = ref<TriggerWayListItem[]>([])
        const loading = ref<boolean>(true)

        /**
         * @description 获取触发方式列表
         */
        const getTriggerWayList = async () => {
            try {
                const res = await getAllExecuteWayList()
                if (!res.success) {
                    console.error(res.message)
                    return
                }
                TriggerWayList.value = res.data

                // 默认选中第一个
                formValue.value['triggerWay'] = res.data[0]?.way

                loading.value = false
            } catch (error) {
                console.error(error)
            }
        }
        
        watch(() => visible.value, (newVal) => {
            if (newVal) {
                getTriggerWayList()
            }
        }, { immediate: true })

        /**
         * @des 相关生成modal的对应的attrs
         * @returns {any}
         */
        const getModalAttrs = ()=> {
            return {
                props: {
                  class:"create-trigger-modal",
                  width: '800px',
                  title: '新建触发器',
                  show: visible.value,
                  appendToBody: true
                },
                on: {
                  'update:show': (value: boolean) => {
                    visible.value = value
                    emit('updateModalValue', value)
                  },
                  'cancel': (value) => {
                    closeDialog()
                  }
                }
              }
        }

        const closeDialog = () => {
            hideDialog()
            setFormValue(initialize(formFields.value, {}))
            setTriggerActiveIndex(0)
        }

        expose({ showDialog, closeDialog })

        /**
         * @des 相关form-builder的更新事件
         * @param {any} field
         * @param {any} newValue
         * @param {any} oldValue
         * @param {any} any>
         * @returns {any}
         */
        const updateFormValue = ({ field, newValue, oldValue }: Record<string, any>)=> {
            const { fieldName } = field
            formValue.value[fieldName] = newValue
        }
        
        /**
         * @des 相关弹窗的确定事件
         * @returns {any}
         */
        const handleConfirm = async () => {
            if(formRef.value) {
                // @ts-ignore
                const validateRes = await formRef.value.validate()
                    if(validateRes) {
                        emit('submit', formValue)
                    }
            }
        }

        /**
         * @des 相关触发方式的点击事件
         * @param {any} item:TriggerWayListItem
         * @param {any} index:number
         * @returns {any}
         */
        const handleTriggerWayItemClick =(item: TriggerWayListItem, index: number)=> {
            formValue.value['triggerWay'] = item.way
            setTriggerActiveIndex(index)
        }

        /**
         * @des 相关触发方式的表单校验事件
         * @param {any} [value
         * @param {any} field]:[string
         * @param {any} Field]
         * @returns {any}
         */
        const validateTriggerWay = ([value, field]: [string, Field]) => {
            return new Promise((resolve, reject)=> {
                if(!value) return resolve('请选择触发方式')
                resolve(null)
            })
        }


        /**
         * @des 弹窗底部组件
         * @returns {any}
         */
        const Footer = ()=> {
            return  (
                <div slot="footer" class="dialog-footer">
                    <el-button type="plain-third" onClick={closeDialog}>{ i18n.t('common.base.cancel') }</el-button>
                    <el-button type="primary" onClick={handleConfirm}>{ i18n.t('common.base.makeSure') }</el-button>
                </div>
            )
        }

        /**
         * @des 打开了解详情
         */
        const goToRealize = ()=> {
            window.open('https://doc.shb.ltd/shb_xoqazk/ia4qctp2ly559d1m/eka8tf9wv8x43arx/dklg7gkm64cya8l4.html')
        }


        /**
         * @des 相关弹窗的触发方式内容组件
         * @param {any} {field
         * @param {any} value}:{field:Field
         * @param {any} value:any}
         * @returns {any}
         */
        const renderTriggerWayList = ({ field, value }: {field: Field, value: any})=> {
            return (
                <form-item 
                    label={field.displayName}
                    propField={field}
                    validation={validateTriggerWay}
                    isNotNull
                >
                    <form-text field={field} value={value} style="display: none"></form-text>
                    <span class="create-trigger-modal__trigger-way-tip">选择一个触发器，通过触发事件或定时任务来触发自动化流程的运行&nbsp;
                        <em onClick={() => goToRealize()}>了解触发器</em>
                    </span>
                    <ul class="create-trigger-modal__trigger-way" v-loading={loading.value}>
                        { TriggerWayList.value.length > 0 && TriggerWayList.value.map((item, index)=> {
                            return (
                            <li class={['create-trigger-modal__trigger-way-item', index === triggerActiveIndex.value ? 'active' : null]} onClick={()=> handleTriggerWayItemClick(item, index)}>
                                <div class="create-trigger-modal__trigger-way-item__icon">
                                    <i class={['iconfont', item.logo]}></i>
                                </div>
                                <div class="create-trigger-modal__trigger-way-item__label">
                                    <h2 class="trigger-way-item__label-title">{item.name}</h2>
                                    <span class="trigger-way-item__label-des">{item.desc}</span>
                                </div>
                            </li>
                            )
                        }) }
                    </ul>
                </form-item>
            )
        }

        return ()=> (
            <base-modal {...getModalAttrs()}>
                <div class="create-trigger-modal__content">
                    <form-builder 
                        class="create-trigger-modal__content-form" 
                        ref={formRef}
                        value={formValue.value}
                        fields={formFields.value} 
                        onUpdate={updateFormValue}
                        scopedSlots={{ triggerWay: renderTriggerWayList }}>
                    </form-builder>
                </div>
               <Footer />
            </base-modal>
        )
    }
})